import { rewriteRouter } from './router/rewriteRouter'
import { setList, getList } from './const/subApps'
import { getCurrentApp } from './utils'
import { setMainLifecycle } from './const/mainLifeCycle'
import { Custom } from './customevent'
import { prefetch } from './loader/prefetch'

const custom = new Custom()
custom.on('test', data => {
  console.log('test data', data)
})
window.custom = custom

// 实现路由拦截
rewriteRouter()

export const registerMicroApps = (appList, lifecycle) => {
  setList(appList)
  // lifecycle.beforeLoad[0]()
  // setTimeout(() => lifecycle.mounted[0](), 3000)
  setMainLifecycle(lifecycle)
}

// 启动微前端框架
export const start = () => {
  // 首先验证当前子应用列表是否为空
  const apps = getList()
  if (apps.length === 0) {
    // 子应用列表为空
    throw new Error('子应用列表为空，请正确注册')
  }

  // 有子应用内容，查找到符合当前路由的子应用
  const currentApp = getCurrentApp()
  if (currentApp) {
    const { pathname, hash } = window.location
    const url = pathname + hash
    window.__CURRENT_SUB_APP__ = currentApp.activeRule
    window.history.pushState(null, null, url)
  }

  // 预加载 - 加载接下来的所有子应用，但是不显示
  prefetch()
}
